<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="编号" prop="examCode">
        <el-input v-model="formData.examCode" placeholder="请输入编号" />
      </el-form-item>
      <el-form-item label="考试名称" prop="examName">
        <el-input v-model="formData.examName" placeholder="请输入考试名称" />
      </el-form-item>
      <el-form-item label="考试类型" prop="examType">
        <el-select v-model="formData.examType" placeholder="请选择考试类型">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="formData.grade" placeholder="请选择年级">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.EXAM_GRADE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学科" prop="subject">
        <el-input v-model="formData.subject" type="textarea" placeholder="请输入学科" />
      </el-form-item>
      <el-form-item label="试卷总分" prop="totalScore">
        <el-input v-model="formData.totalScore" placeholder="请输入试卷总分" />
      </el-form-item>
      <el-form-item label="题目总数" prop="questionCount">
        <el-input v-model="formData.questionCount" placeholder="请输入题目总数" />
      </el-form-item>
      <el-form-item label="答题卡类型" prop="answerCardType">
        <el-select v-model="formData.answerCardType" placeholder="请选择答题卡类型">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="原始试卷文件路径" prop="originalPaperUrl">
        <el-input v-model="formData.originalPaperUrl" placeholder="请输入原始试卷文件路径" />
      </el-form-item>
      <el-form-item label="答题卡模板文件路径" prop="answerCardTemplateUrl">
        <el-input v-model="formData.answerCardTemplateUrl" placeholder="请输入答题卡模板文件路径" />
      </el-form-item>
      <el-form-item label="标准答案文件路径" prop="standardAnswerUrl">
        <el-input v-model="formData.standardAnswerUrl" placeholder="请输入标准答案文件路径" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ExamApi, Exam } from '@/api/exam/exam'

/** 考试管理 表单 */
defineOptions({ name: 'ExamForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  examCode: undefined,
  examName: undefined,
  examType: undefined,
  grade: undefined,
  subject: undefined,
  totalScore: undefined,
  questionCount: undefined,
  answerCardType: undefined,
  originalPaperUrl: undefined,
  answerCardTemplateUrl: undefined,
  standardAnswerUrl: undefined,
  status: undefined,
})
const formRules = reactive({
  examCode: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  examName: [{ required: true, message: '考试名称不能为空', trigger: 'blur' }],
  grade: [{ required: true, message: '年级不能为空', trigger: 'change' }],
  subject: [{ required: true, message: '学科不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ExamApi.getExam(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Exam
    if (formType.value === 'create') {
      await ExamApi.createExam(data)
      message.success(t('common.createSuccess'))
    } else {
      await ExamApi.updateExam(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    examCode: undefined,
    examName: undefined,
    examType: undefined,
    grade: undefined,
    subject: undefined,
    totalScore: undefined,
    questionCount: undefined,
    answerCardType: undefined,
    originalPaperUrl: undefined,
    answerCardTemplateUrl: undefined,
    standardAnswerUrl: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}
</script>